package com.ctshk.common.utils;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;

import java.util.*;

public class MaptoXmlUtil {

    /**
     * 功能描述: Map 转 Xml字符串
     */
    public static String map2Xml(Map<String, String> paras) {
        SortedMap<String, String> paraMap = new TreeMap<String, String>();
        paraMap.putAll(paras);
        String xmlStr = "<xml>";
        Set es = paraMap.entrySet();
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            String v = (String) entry.getValue();
            xmlStr += "<" + k + ">" + v + "</" + k + ">";
        }
        xmlStr += "</xml>";
        return xmlStr;
    }

    /**
     * 功能描述: XML字符串 转 Map
     */
    public static Map<String, String> xml2Map(String xmlStr) throws Exception {
        // TODO
        Map<String, String> rtnMap = new HashMap<String, String>();
        Document doc = null;
        try {
            doc = DocumentHelper.parseText(xmlStr);//通过DOM4J解析XML字符串
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        //得到根节点
        Element root = doc.getRootElement();
        // 获取所有子元素
        for (Iterator i = root.elementIterator(); i.hasNext(); ) {
            Element el = (Element) i.next();
            rtnMap.put(el.getName(), el.getText());

        }
        return rtnMap;
    }


}